package com.nbcio.modules.erp.coupon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.modules.erp.cart.entity.Cart;
import com.nbcio.modules.erp.cart.entity.CartItems;
import com.nbcio.modules.erp.cart.service.CartItemsService;
import com.nbcio.modules.erp.cart.service.CartService;
import com.nbcio.modules.erp.coupon.entity.MallCoupon;
import com.nbcio.modules.erp.coupon.entity.OrderCouponRelations;
import com.nbcio.modules.erp.coupon.entity.UserCouponRelations;
import com.nbcio.modules.erp.coupon.mapper.MallCouponMapper;
import com.nbcio.modules.erp.coupon.service.IMallCouponService;
import com.nbcio.modules.erp.coupon.service.OrderCouponRelationsService;
import com.nbcio.modules.erp.coupon.service.UserCouponRelationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 优惠券
 * @Author: nbacheng
 * @Date:   2024-04-16
 * @Version: V1.0
 */
@Service
public class MallCouponServiceImpl extends ServiceImpl<MallCouponMapper, MallCoupon> implements IMallCouponService {

    @Autowired
    private UserCouponRelationsService userCouponRelationsService;

    @Autowired
    private OrderCouponRelationsService orderCouponRelationsService;

    @Autowired
    private CartService cartService;

    @Autowired
    private CartItemsService cartItemsService;


    /**
     * 查询出用户未领取的优惠券
     * @param map
     * @return
     */
    @Override
    public List<MallCoupon> queryMallCoupon(Map<String, Object> map) {
        //查询所有的有效期内的折扣券，固定金额券，满足金额的免减券，免运费券，该品类券，该品券，以及数量还有，以及单用户领取次数大于用户领取次数

        List<MallCoupon> mallCouponsList = queryUserCouponByUserId(map);
        if (CollectionUtil.isNotEmpty(mallCouponsList)){
            List<String> idList = mallCouponsList.stream().map(MallCoupon::getId).collect(Collectors.toList());
            List<MallCoupon> allMallCouponList = list();

            return allMallCouponList.stream().filter(i->!idList.contains(i.getId())).collect(Collectors.toList());
        }
        return list();
    }

    /**
     * 查询用户领取的优惠券
     * @param map
     * @return
     */
    @Override
    public List<MallCoupon> queryUserCouponByUserId(Map<String, Object> map) {

        String user_id = map.get("user_id").toString();
        LambdaQueryWrapper<UserCouponRelations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCouponRelations::getUserId, user_id);
        List<UserCouponRelations> userCouponRelationsList = userCouponRelationsService.list(wrapper);
        if (CollectionUtil.isNotEmpty(userCouponRelationsList)) {
//            List<UserCouponRelations> collect = userCouponRelationsList.stream().filter(i -> (i.getUseNum().compareTo(i.getIssueNum())) < 0).collect(Collectors.toList());
            List<String> couponIdList = userCouponRelationsList.stream().map(UserCouponRelations::getCouponId).collect(Collectors.toList());
            List<MallCoupon> mallCouponList = listByIds(couponIdList);
            if (CollectionUtil.isNotEmpty(mallCouponList)){
                return mallCouponList.stream().filter(mall->mall.getRemainingQuantity().compareTo(BigDecimal.ZERO)>0).collect(Collectors.toList());
            }

            return new ArrayList<>();
        }

        return new ArrayList<>();
    }


    /**
     * 领取优惠券
     * @param map
     */
    @Override
    @Transactional
    public void ReceiveCouponById(Map<String, Object> map) {

        String user_id = map.get("user_id").toString();
        String coupon_id = map.get("coupon_id").toString();
        //判断这个用户有没有领取过这个优惠券
        LambdaQueryWrapper<UserCouponRelations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCouponRelations::getUserId, user_id)
                .eq(UserCouponRelations::getCouponId, coupon_id);

        if (userCouponRelationsService.count(wrapper)>0){
            UserCouponRelations userCouponRelations = userCouponRelationsService.getOne(wrapper);
            userCouponRelations.setNum(userCouponRelations.getNum().add(BigDecimal.ONE));
            userCouponRelationsService.updateById(userCouponRelations);
        }else {

            UserCouponRelations userCouponRelations = new UserCouponRelations();
            userCouponRelations.setCouponId(coupon_id);
            userCouponRelations.setUserId(user_id);
            userCouponRelations.setId(RandomUtil.randomString(32));
            userCouponRelations.setAcquiredAt(new Date());
            userCouponRelations.setNum(BigDecimal.ONE);

            userCouponRelationsService.save(userCouponRelations);
        }

        //领取了优惠券，那么对应的优惠券数量要改变
        //查出对应的优惠券
//        MallCoupon mallCoupon = getById(coupon_id);
//        mallCoupon.setRemainingQuantity(mallCoupon.getRemainingQuantity().subtract(BigDecimal.ONE));
//        mallCoupon.setUsedQuantity(mallCoupon.getUsedQuantity().add(BigDecimal.ONE));
//        updateById(mallCoupon);
    }

    /**
     * 订单生成之后的处理
     * @param map
     */
    @Override
    @Transactional
    public void afterSaveOrder(Map<String, Object> map) {

        String type = map.get("type").toString();
        String user_id = map.get("user_id").toString();
        String couponId = (map.get("coupon_id") == null || "".equals(map.get("coupon_id"))) ? "" : map.get("coupon_id").toString();

        //是否是从购物车生成订单，是的话对应的购物车清除
        if (type.equals("cart")){
            JSONArray cartArray = JSON.parseArray(JSON.toJSONString(map.get("cart")));
            for (int i = 0; i < cartArray.size(); i++) {
                JSONObject cartObj = cartArray.getJSONObject(0);
                String id = cartObj.getString("id");
                BigDecimal num = cartObj.getBigDecimal("num");

                LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Cart::getUserId, user_id);
                Cart cart = cartService.getOne(wrapper);

                if (cart!=null){
                    List<CartItems> cartItemsList = cartItemsService.queryByMainId(cart.getId());
                    int size = cartItemsList.size();
                    for (CartItems cartItems : cartItemsList) {
                        if (cartItems.getId().equals(id)){
                            if (cartItems.getQuantity().compareTo(num)==0){
                                cartItemsService.removeById(id);
                                size--;
                            }else if (cartItems.getQuantity().compareTo(num)>0){
                                cartItems.setQuantity(cartItems.getQuantity().subtract(num));
                                cartItemsService.updateById(cartItems);
                            }
                        }
                    }

                    //最后看购物车明细是否还有，没有的话删除
                    if (size==0){
                        cartService.removeById(cart.getId());
                    }
                }

            }
        }

        String orderId  = map.get("order_id").toString();

        //订单生成之后，优惠券要减去数量

        if (!"".equals(couponId)) {

            MallCoupon mallCoupon = getById(couponId);

            if (mallCoupon.getRemainingQuantity().compareTo(BigDecimal.ONE) >= 0) {
                mallCoupon.setRemainingQuantity(mallCoupon.getRemainingQuantity().subtract(BigDecimal.ONE));
                mallCoupon.setUsedQuantity(mallCoupon.getUsedQuantity().add(BigDecimal.ONE));
                updateById(mallCoupon);
            }
            //订单生成之后，生成订单优惠券关联记录
            OrderCouponRelations couponRelations = new OrderCouponRelations();
            couponRelations.setCouponId(couponId);
            couponRelations.setOrderId(orderId);
            couponRelations.setId(RandomUtil.randomString(32));
            couponRelations.setCreatedAt(new Date());
            couponRelations.setDiscountAmount(mallCoupon.getAmount());
            orderCouponRelationsService.save(couponRelations);
            //订单生成之后，更改用户优惠券状态、使用数量等

            LambdaQueryWrapper<UserCouponRelations> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserCouponRelations::getUserId, user_id)
                    .eq(UserCouponRelations::getCouponId, couponId);

            UserCouponRelations userCouponRelations = userCouponRelationsService.getOne(wrapper);
            if (userCouponRelations == null) {
                throw new RuntimeException("未查到对应的用户优惠券关联记录，请联系管理员");
            }

            userCouponRelations.setUpdatedAt(new Date());
            userCouponRelations.setStatus("used");
            userCouponRelations.setUseNum(userCouponRelations.getUseNum().add(BigDecimal.ONE));
            userCouponRelations.setUsedAt(new Date());

            userCouponRelationsService.updateById(userCouponRelations);
        }
    }
}
